<?php

namespace app\admin\service;

use app\common\model\trOutletsSurcharge;
use app\common\util\ErrorCode;

/**
 * Class SurchargeService
 * @package app\admin\service
 * 网点附加费用服务类
 */
class SurchargeService extends BaseService
{
    protected $field = [
        "name" => self::FIELD_REQUIRE, "price" => self::FIELD_REQUIRE, "mode" => self::FIELD_REQUIRE,
        "desc" => "",
    ]; //填入数据库需要存储的表字段

    // 获取网点列表
    public function getList(){
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;

        $db = trOutletsSurcharge::where(["mall_id" => $this->mall_id]);
        $data = $db->paginate(["list_rows" => $pageSize, "page" => $page]);
        $this->returnData["data"] = $this->convertPageData($data);
        return $this->returnData;
    }

    public function toAdd(){
        $data = $this->extractData([
            "mall_id" => $this->mall_id, "create_time" => time(), "update_time" => time()
        ]);
        $model = trOutletsSurcharge::create($data);
        if(!$model->id){
            $this->returnData = ErrorCode::code("customized", "添加失败");
        }else{
            $this->returnData["msg"] = "添加成功";
        }
        return $this->returnData;
    }

    public function toEdit(){
        if(empty($this->params["id"])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $database = trOutletsSurcharge::where("id", $this->params["id"])->find();
        if(empty($database)){
            return  ErrorCode::code("customized", "数据不存在");
        }
        $data = $this->extractData(["update_time" => time()]);
        $database->data($data);
        $database->save();
        $this->returnData["msg"] = "更新成功";
        return $this->returnData;
    }

    public function toUpdateStatus(){
        if(empty($this->params["id"])){
            return ErrorCode::code("params_not_exist", "id");
        }
        /** @var trOutletsSurcharge $database */
        $database = trOutletsSurcharge::where("id", $this->params["id"])->find();
        if(empty($database)){
            return  ErrorCode::code("customized", "数据不存在");
        }
        $database->status = $database->status === 1 ? 2 : 1;
        $database->save();
        $this->returnData["msg"] = "更新成功";
        return $this->returnData;
    }

    public function toDel(){
        if(empty($this->params["id"])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $database = trOutletsSurcharge::where("id", $this->params["id"])->find();
        if(empty($database)){
            return  ErrorCode::code("customized", "数据不存在");
        }
        $database->delete();
        $this->returnData["msg"] = "删除成功";
        return $this->returnData;
    }
}